<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>登录</title>
    <!-- 样式文件 -->
    <link th:href="@{/pear/component/pear/css/pear.css}" type="text/css" rel="stylesheet"/>
    <link rel="stylesheet" th:href="@{/pear/admin/css/other/login.css}"/>
    <link rel="stylesheet" th:href="@{/pear/css/slidercaptcha.css}">
    <link rel="stylesheet" th:href="@{/pear/css/css2.css}">
    <link rel="stylesheet" th:href="@{/pear/css/all.min.css}">
    <style>
        body {
            margin: 0;
            padding: 0;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            background-size: cover;
            background-position: center;
        }

        .login-container {
            display: flex;
            background-color: #fff;
            padding: 40px;
            box-sizing: border-box;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            width: 1050px;
            height: 600px;
        }

        .company-image {
            flex: 1;
            padding: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .company-image img {
            max-width: 100%;
            max-height: 100%;
        }

        .vertical-line {

            width: 1px;
            background-color: #ccc;
            margin: 20px 10px;
        }

        .login-form-container {
            flex: 1;
            padding: 20px;
        }

        .layui-form {
            justify-content: center;
            align-items: center;
            margin-top: 0px !important;
        }

        /* 新增或修改滑动验证码容器样式 */
        .slider-container {
            margin-left: 260px;
            width: 350px; /* 根据需要调整宽度 */
            height: 300px; /* 根据需要调整高度 */
        }

        /* 提示文本样式 */
        .captcha-instruction {
            text-align: center;
            font-size: 16px;
            margin-bottom: 20px;
        }
    </style>
</head>
<!--代码结构-->
<body style="background-size: cover;">
<div class="login-container">
    <!-- 公司图片 -->
    <div class="company-image">
        <img th:src="@{/pear/admin/images/company-image.png}" alt="公司Logo"/>
    </div>
    <!-- 垂直分割线 -->
    <div class="vertical-line"></div>
    <!-- 登录表单 -->
    <div class="login-form-container" style="margin-top: 60px;">
        <form class="layui-form" method="POST" id="loginForm" autocomplete="off">
            <div class="layui-form-item" style="margin-bottom: 45px">
                <img class="logo" th:src="@{/pear/admin/images/logo.png}"/>
                <div class="title">内容管理系统</div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-wrap">
                    <div class="layui-input-prefix">
                        <i class="layui-icon layui-icon-username"></i>
                    </div>
                    <input type="text" name="uname" maxlength="15" lay-verify="required|uname" autocomplete="off"
                           placeholder="请输入用户名"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-wrap">
                    <div class="layui-input-prefix">
                        <i class="layui-icon layui-icon-password"></i>
                    </div>
                    <input type="password" name="pwd" lay-verify="required|pwd" placeholder="密码" autocomplete="off"
                           class="layui-input" lay-affix="eye">
                </div>
            </div>

            <!--            <div class="layui-form-item">-->
            <!--                <input type="checkbox" name="remember" lay-skin="primary" title="记住密码">-->
            <!--            </div>-->
            <div class="layui-form-item">
                <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="demo-login" id="login-btn">登录
                </button>
            </div>
        </form>
        <!-- 图形验证码弹出层 -->
        <div id="captchaModal" class="slider-container"
             style="display:none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 1000; background-color: white; padding: 20px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);">
            <div id="captchaContainer">
                <i class="layui-icon close-btn layui-icon-close"></i>
                <div class="captcha-instruction">请完成图形验证</div>
                <div id="sliderCaptchaContainer"></div>
            </div>
        </div>
    </div>
    <div th:if="${script}" th:utext="${script}"></div>
</div>
<!-- 资源引入 -->
<script th:src="@{/pear/component/layui/layui.js}"></script>
<script th:src="@{/pear/component/pear/pear.js}"></script>
<script th:src="@{/pear/component/jquery/jquery.min.js}"></script>
<script th:src="@{/pear/js/crypto-js.min.js}"></script>
<script th:src="@{/pear/js/longbow.slidercaptcha.js}"></script>
<script th:inline="javascript">

    layui.use(['form', 'jquery', 'layer'], function () {
        let form = layui.form;
        let $ = layui.jquery;
        let layer = layui.layer;
        let baseURL = /*[[@{/}]]*/ '';
        form.verify({
            // 验证用户名，且为必填项
            uname: function (value) {
                // 正则表达式，只允许字母、数字和下划线，且不能以下划线开始
                if (!new RegExp("^[a-zA-Z0-9][a-zA-Z0-9_]*$").test(value)) {
                    return '请输入有效的用户名';
                }
            },
            pwd: function (value) {
                if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[~!@&%#_])[a-zA-Z0-9~!@&%#_]{8,20}$/.test(value)) {
                    return '请输入有效密码';
                }
            },
        });
        // 使用AES加密密码
        let key = CryptoJS.enc.Utf8.parse('3f5279c6d4a12f58'); // 密钥应该是一个保密的字符串
        let iv = CryptoJS.enc.Utf8.parse('d4e2f6a0b8c0d2e8'); // 初始化向量，可以是任意值，但解密时需要相同
        let customX = 200
        let captchaId = null
        // 关闭验证码模态框
        $('.close-btn').click(function () {
            $('#captchaModal').hide();
        });
        $(document).ready(function () {
            $.ajax({
                url: baseURL + 'captcha/generate',
                method: 'GET',
                dataType: 'json',
                success: function (response) {
                    if (response) {
                        // 更新背景图片

                        // 更新验证码ID
                        captchaId = response.captchaId;
                        // 更新缺口横坐标
                        customX = response.correctX;
                    }
                }
            })

            //初始化图形验证码

            $('#sliderCaptchaContainer').sliderCaptcha({
                reset: false,
                repeatIcon: 'fa fa-redo',
                customX: Number(customX),
                setSrc: function () {
                    // 从后端获取验证码图片
                    return baseURL + 'pear/admin/images/avatar' + (Math.floor(Math.random() * (4)) + 2) + '.jpeg';
                },
                onSuccess: function () {
                    let userX = parseInt($('#sliderCaptchaContainer').find('.slider').css('left'), 10)
                    console.log(userX);
                    $('#captchaModal').hide();
                    login(captchaId, userX)

                },
                onFail: function () {
                    // 滑动失败后的回调
                    $.ajax({
                        url: baseURL + 'captcha/generate',
                        method: 'GET',
                        dataType: 'json',
                        success: function (response) {
                            if (response) {
                                // 更新背景图片

                                // 更新验证码ID
                                captchaId = response.captchaId;
                                // 更新缺口横坐标
                                customX = response.correctX;
                                $('#sliderCaptchaContainer').sliderCaptcha({
                                    reset: true,
                                    customX: Number(customX),
                                    failFlag: true,
                                    setSrc: function () {
                                        // 从后端获取验证码图片
                                        return baseURL + 'pear/admin/images/avatar' + (Math.floor(Math.random() * (4)) + 2) + '.jpeg';
                                    }
                                })
                                $('#sliderCaptchaContainer').removeClass('success');
                            }
                        }
                    })

                },
                onRefresh: function () {
                    // 刷新后的回调
                    $.ajax({
                        url: baseURL + 'captcha/generate',
                        method: 'GET',
                        dataType: 'json',
                        success: function (response) {
                            if (response) {
                                // 更新背景图片

                                // 更新验证码ID
                                captchaId = response.captchaId;
                                // 更新缺口横坐标
                                customX = response.correctX;
                                $('#sliderCaptchaContainer').sliderCaptcha({
                                    reset: true,
                                    customX: Number(customX),
                                    setSrc: function () {
                                        // 从后端获取验证码图片
                                        return baseURL + 'pear/admin/images/avatar' + (Math.floor(Math.random() * (4)) + 2) + '.jpeg';
                                    }
                                })
                                $('#sliderCaptchaContainer').removeClass('success');
                            }
                        }
                    })
                }
            });


        });

        let uname = "";
        let pwd = "";
        // 登录提交
        form.on('submit(demo-login)', function (data) {
            event.preventDefault();
            let encryptedPwd = CryptoJS.AES.encrypt(data.field.pwd, key, {
                iv: iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7
            });
            data.field.pwd = encryptedPwd.toString();
            $('#captchaModal').show();
            uname = data.field.uname
            pwd = data.field.pwd
            $.ajax({
                url: baseURL + 'captcha/generate',
                method: 'GET',
                dataType: 'json',
                success: function (response) {
                    if (response) {
                        // 更新验证码ID
                        captchaId = response.captchaId;
                        // 更新缺口横坐标
                        customX = response.correctX;
                        $('#sliderCaptchaContainer').sliderCaptcha({
                            reset: true,
                            customX: Number(customX),
                            setSrc: function () {
                                // 从后端获取验证码图片
                                return baseURL + 'pear/admin/images/avatar' + (Math.floor(Math.random() * (4)) + 2) + '.jpeg';
                            }
                        })
                        $('#sliderCaptchaContainer').removeClass('success');
                    }
                }
            })
            return false; // 阻止表单默认提交
        });

        let login = function (captchaId, userX) {
            $('#login-btn').prop('disabled', true);
            let loading = layer.msg('登录中...', {icon: 16, shade: 0.3, time: 0});
            $.ajax({
                type: 'POST',
                url: baseURL + 'user/login', // 后端登录接口的URL
                contentType: 'application/json', // 设置content-type头部
                data: JSON.stringify({
                    uname: uname,
                    pwd: pwd,
                    captchaId: captchaId,
                    userX: userX
                }),
                success: function (res) {
                    if (res.code === 200) {
                        layer.close(loading)
                        layer.msg('登录成功', {icon: 1, time: 2000}, function () {
                            // 跳转到主页
                            location.href = baseURL + "page/index"; // 确保这是正确的URL
                        });
                    } else {
                        layer.close(loading)
                        $('#login-btn').prop('disabled', false);
                        layer.msg(res.msg, {icon: 2, anim: 6});
                    }
                },
                error: function (jqXHR, textStatus, errorThrown, res) {
                    layer.close(loading)
                    $('#login-btn').prop('disabled', false);
                    // 处理AJAX请求失败的情况
                    let errorMessage = textStatus + ':' + errorThrown;
                    if (jqXHR.responseText) {
                        errorMessage = "用户名或密码错误";
                    }
                    layer.msg(errorMessage, {icon: 2, anim: 6});
                }
            });

        }
    });

</script>
</body>
</html>